/****************************************************************************************** Import */
import _ from 'lodash';
import Storage from '../../basis/storage';
import Session from '../../basis/session';
import Gen from '../../basis/gen';
import App from '../../../../../config/global/app';

/****************************************************************************************** Class */
export default class Sign {

    /**
     * 初始化sign
     * 
     * @param {Object} sign 用户标记对象。注意：此值是由arrive传来的，从Storage取出，有时为null
     */
    static init(sign) {

        // 如果不存在sign值，或是sign的格式不正确，则初始化为默认空sign，并保存回去
        if (sign == null || !(_.has(sign, 'token') && _.has(sign, 'uid'))) {
            sign = sign = { token: '', uid: 0 };
            Storage.set('system_user_sign', sign);
        }
        
        // 制作初始arrive、httpheaders
        const arrive = Gen.mixed(32);
        const httpHeaders = {
            token: sign.token,
            uid: sign.uid,
            arrive: arrive,
            platform: App.platform,
            appname: App.appname,
            version: App.version
        }

        // 将sign和httpHeaders存入session
        Session.set('system_user_sign', sign);
        Session.set('system_http_auths', httpHeaders);
    }

    /**
     * 刷新sign
     * 
     * @param {Object} sign 用户标记对象
     */
    static refresh(sign) {

        // 将新的sign更新到httpheaders
        const httpHeaders = Session.get('system_http_auths');
        httpHeaders.token = sign.token;
        httpHeaders.uid = sign.uid;

        // 将新的sign存入storage
        Storage.set('system_user_sign', sign);

        // 将新的sign和httpheaders存入session
        Session.set('system_user_sign', sign);
        Session.set('system_http_auths', httpHeaders);
    }

    /**
     * 仅将将uid设置为0，通常用在用户退出
     */
    static clearUid() {

        // 取httpheaders，并将uid设置为0
        const httpheaders = Session.get('system_http_auths');
        httpHeaders.uid = 0;

        // 根据httpheaders，设置一个新的sign对象
        const sign = { token: httpheaders.token, uid: 0 };

        // 将sign存入storage
        Storage.set('system_user_sign', sign);

        // 将sign和httpheaders存入session
        Session.set('system_user_sign', sign);
        Session.set('system_http_auths', httpHeaders);
    }
}
